#pragma once

#include <iostream>
#include <string>
#include <memory>

#include "Socket.hpp"
#include "TcpServer.hpp"
#include "InetAddr.hpp"
#include "HttpProtocol.hpp"

using namespace My_Socket;

using task_t = std::function<void()>;

class HttpServer
{
private:
    void HanderRequest(SockPtr &sockptr, InetAddr &cliaddr)
    {
        std::string recvstr;
        while (true)
        {
            int n = sockptr->Recv(recvstr);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << "Recv fail!";
                continue;
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client close, client# " << cliaddr.GetStrIpPort();
                break;
            }

            LOG(LogLevel::INFO) << "recvbuf is : " << recvstr;

            HttpRequest req;
            req.Deserialize(recvstr);

            // std::string resstr = _hander(recvstr);
            // LOG(LogLevel::INFO) << "result is : " << resstr;
            // socket.Send(resstr);
        }
    }

public:
    HttpServer(int port) : _tcpserver(std::make_unique<TcpServer>(port))
    {
    }
    void Start()
    {
        _tcpserver->InitServer([this](SockPtr sockptr, InetAddr addr)
                               { this->HanderRequest(sockptr, addr); });
        _tcpserver->Loop();
    }
    ~HttpServer()
    {
    }

private:
    std::unique_ptr<TcpServer> _tcpserver;
};